<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 用户管理
 */
class AppipaController extends Controller
{
    //前置操作方法
    public function _before_index()
    {
        $xxid = trim(I('xxid'));

        $model = M('List');

        $where['id'] = $xxid;

        $res = $model->where($where)->find();
        if (!isset($res)) {
            $this->display('error');
            die;
        }
        $ttid = session('homeId') ? session('homeId') : $res['fid'];
        $rests = M("Member")->where(array('id' => $ttid))->find();
        $this->meminfo = $rests;
    }

    public function _empty()
    {
        redirect(U('Index/listinfo'));
    }

    public function listll()
    {

        $passid = trim(I('passid'));
        $aqpassword = session('aqpassword' . $passid);

        if (!empty($passid) && !empty($aqpassword)) {

            $model = M('List');
            $where['id'] = $passid;

            $upid = $model->where($where)->getField('upid');
            if ($upid !== '0') {
                $where['id'] = $upid;
            }

            //$where['aqpassword'] = $aqpassword;
            $list = $model->where($where)->find();

            $this->aqpassword = $aqpassword;
            $this->list = $list;
            $moban = ($list['mobanid']+1);
            $array = AppipaController::gopayurl($list);
            session('aqpassword' . $passid, null);
            $gopayurl  = $array["gopayurl"];
            $userid =  $array["userid"];
            $ispayed = $array["ispayed"];
            //  $moban =  $array["moban"];
            $this->gopayurl=$gopayurl; //如果两个需要返回两个数据

            $this->userid = $userid; //返回一个
            $this->ispayed = $ispayed;
            $uptype = M("Member")->where(array('id' => $list['fid']))->getField('uptype');
            $this->uptype = $uptype;

            $this->display('moban_'.$moban);
        } else {
            $this->error("请从新输入密码", U("Index/listinfo"));
        }

    }

    public function index()
    {

        $xxid = trim(I('xxid'));
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: http://' . $_SERVER['SERVER_NAME'] . '/a/' . $xxid);
        exit;
        $model = M('List');

        $where['id'] = $xxid;
        $upid = $model->where($where)->getField('upid');
        if ($upid !== '0') {
            $where['id'] = $upid;
        }
        $res = $model->where($where)->setInc('xznum', '1');
        $list = $model->where($where)->find();


        $uptype = M("Member")->where(array('id' => $list['fid']))->getField('uptype');

        $this->uptype = $uptype;
        $this->list = $list;
        if ($list['upid'] !== '0') {

            $web = '/index.php/so/' . $list['upid'];
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . '/' . $web, $list['upid']);
        } else {
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . '/' . $list['web'], $list['id']);
        }

        $this->display();
    }

    public function index4()
    {
        $ispayed = 0;
        //获取 路径
        $xxid = trim(I('xxid'));

        $model = M('List');
        $where = array();
        //路径赋值给shorturl 字段方便查找
        $where['shorturl'] = $xxid;
        $upid = $model->where($where)->getField('upid');
        //该字段不清楚是什么意思 应该是upid 应该是升级版本吧
        if ($upid !== '0') {
            $where = array();
            $where['id'] = $upid;
        }
        //根据网页查询
        $list = $model->where($where)->find();
        //没有结果跳转到错误页面
        if (!$list) {
            redirect(U('Login/nopage'));
            exit;
        }
        //实例化合并页面
        $hebing = M("Hebing");
        $where = array();
        //根据listid 查询hebing表中的appid 两个字段值是相等的
        $where['appid'] = $list['id'];
        $apparr = $hebing->where($where)->select();
        //echo "<pre>";print_r($apparr);
        //判断是否有结果
        if ($apparr) {
            $isios = '0';//手机登录判断
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
                $isios = '1';
            } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
                $isios = '0';
            }
            $newid = 0;
            if ($list['ext'] == 'ipa') {

                if (!$isios) {
                    foreach ($apparr as $val) {
                        $appinfoarr = $model->where(array('id' => $val['toaddid']))->find();
                        if ($appinfoarr['ext'] != 'ipa') {
                            $newid = $appinfoarr['id'];
                            break;
                        }
                    }
                }
            } else {

                if ($isios) {
                    foreach ($apparr as $val) {

                        $appinfoarr = $model->where(array('id' => $val['toaddid']))->find();
                        if ($appinfoarr['ext'] == 'ipa') {
                            $newid = $appinfoarr['id'];
                            break;
                        }
                    }
                }
            }

            if ($newid) {
                $list = $model->where(array('id' => $newid))->find();
                if (!$list) {
                    redirect(U('Login/nopage'));
                    exit;
                }
            }
        }
        //$res = $model->where(array('id'=>$list['id']))->setInc('xznum','1');

        $downhistory = M("Downhistory");
        $nowtime = time();
        $data = array();
        $data['appid'] = $list['id'];
        $data['addtime'] = date('Y-m-d H:i:s', $nowtime);
        $data['type'] = '0';
        $downhistory->add($data);

        $uptype = M("Member")->where(array('id' => $list['fid']))->getField('uptype');

        $this->uptype = $uptype;
        $this->list = $list;
        //echo $list['upid'];exit;
        if ($list['upid'] !== '0') {
            //$web = 'a/'.$list['shorturl'];
            //$this->qrcode = $this->qrcode('http://'.$_SERVER['SERVER_NAME'].'/'.$web,$list['upid']);
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . $list['web'], $list['id']);
        } else {
            //echo "[".'http://'.$_SERVER['SERVER_NAME'].$list['web']."]";exit;
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . $list['web'], $list['id']);
        }
        $moban = 'moban_' . ($list['mobanid'] + 1);


        if ($list['needmoney'] == 0) {
            $ispayed = '1';
        }

        if ($list['needmoney'] == 1) {
            $userarr = M('Member')->where(array('id' => session('homeId')))->find();
            $fuserarr = M('Member')->where(array('id' => $list['fid']))->find();


            $appsize = formatBytesMb($list['zsize']);
            $neednum = 1;
            $config = M("Config")->find();
            $filesizearr = explode(',', $config['filesizearr']);
            $downnumarr = explode(',', $config['downnumarr']);
            foreach ($filesizearr as $k => $val) {
                if ($appsize > $val) {
                    $neednum = $downnumarr[$k];
                }
            }
            if ($fuserarr['everydaynum'] >= $neednum) {
                $ispayed = '1';
            } else {
                if ($fuserarr['downnum'] >= $neednum) {
                    $ispayed = '1';
                } else {
                    $ispayed = '0';
                }
            }


        }
        $payedcount = M("taocanorder")->where(array('userid' => session('homeId'), 'listid' => $list['id'], 'status' => '1'))->count();
        if ($payedcount) {
            $ispayed = '1';
        }
        if (session('homeId')) {
            $userid = session('homeId');
        } else {
            $userid = 0;
        }

        if (is_mobile()) {
            $gopayurl = '/alipay/wappay/payapp.php?listid=' . $list['id'] . '&userid=' . $userid . '&buymoney=' . $list['needmoney'] . '';
        } else {
            $gopayurl = '/alipaypc/pagepay/payapp.php?listid=' . $list['id'] . '&userid=' . $userid . '&buymoney=' . $list['needmoney'] . '';
        }

        $gopayurl = U("Appipa/buyapp", array('id' => $list['id']));
        $this->assign('gopayurl', $gopayurl);

        $this->userid = $userid;
        $this->ispayed = $ispayed;
        $this->display($moban);
    }


    public function buyapp()
    {

        $xxid = trim(I('id'));

        $model = M('List');
        $where = array();
        $where['id'] = $xxid;
        $list = $model->where($where)->find();
        if (!$list) {
            redirect(U('Login/nopage'));
            exit;
        }
        $this->list = $list;

        if (session('homeId')) {
            $userid = session('homeId');
        } else {
            $this->error("未登录，请先登录", U("Login/index"));
            exit;
        }

        if (is_mobile()) {
            $alipayurl = '/alipay/wappay/payapp.php?listid=' . $list['id'] . '&userid=' . $userid . '&buymoney=' . $list['needmoney'] . '';
        } else {
            $alipayurl = '/alipaypc/pagepay/payapp.php?listid=' . $list['id'] . '&userid=' . $userid . '&buymoney=' . $list['needmoney'] . '';
        }
        $jiupayurl = '/jiupay/payapp.php?listid=' . $list['id'] . '&userid=' . $userid . '&buymoney=' . $list['needmoney'] . '';

        $this->assign('alipayurl', $alipayurl);

        $this->assign('jiupayurl', $jiupayurl);

        if (is_mobile()) {
            $this->assign('ispc', '0');
        } else {
            $this->assign('ispc', '1');
        }

        $this->display();
    }

    public function index3()
    {

        $xxid = trim(I('xxid'));

        $model = M('List');
        $where = array();
        $where['shorturl'] = $xxid;
        $upid = $model->where($where)->getField('upid');
        if ($upid !== '0') {
            $where = array();
            $where['id'] = $upid;
        }

        $list = $model->where($where)->find();
        if (!$list) {
            redirect(U('Login/nopage'));
            exit;
        }
        $hebing = M("Hebing");
        $where = array();
        $where['appid'] = $list['id'];
        $listnew = array();
        $apparr = $hebing->where($where)->order("id desc")->find();
        if ($apparr) {
            $appinfoarr = $model->where(array('id' => $apparr['toaddid']))->find();
        }
        $this->listnew = $appinfoarr;
        //echo "<pre>";print_r($apparr);

        //$res = $model->where(array('id'=>$list['id']))->setInc('xznum','1');

        $downhistory = M("Downhistory");
        $nowtime = time();
        $data = array();
        $data['appid'] = $list['id'];
        $data['addtime'] = date('Y-m-d H:i:s', $nowtime);
        $data['type'] = '0';
        $downhistory->add($data);

        $uptype = M("Member")->where(array('id' => $list['fid']))->getField('uptype');

        $this->uptype = $uptype;
        $this->list = $list;
        //echo $list['upid'];exit;
        if ($list['upid'] !== '0') {
            //$web = 'a/'.$list['shorturl'];
            //$this->qrcode = $this->qrcode('http://'.$_SERVER['SERVER_NAME'].'/'.$web,$list['upid']);
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . $list['web'], $list['id']);
        } else {
            //echo "[".'http://'.$_SERVER['SERVER_NAME'].$list['web']."]";exit;
            $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . $list['web'], $list['id']);
        }

        $this->display();
    }

    public function duo()
    {

        $xxid = trim(I('xxid'));
        $model = M('Newlist');
        $where['id'] = $xxid;
        $res = $model->where($where)->setInc('xznum', '1');
        $list = $model->where($where)->find();
        if (!isset($list)) {
            $this->error("请正确输入地址", U("Index/yeshb"));
        }


        $tid = explode(',', $list['tid']);
        $tname = explode(',', $list['tname']);
        $tweb = explode(',', $list['tweb']);


        $info = array();
        for ($i = 0; $i < count($tid); $i++) {
            $info[$i]['tname'] = $tname[$i];
            $info[$i]['tweb'] = $tweb[$i];

        }

        $this->info = $info;
        $this->list = $list;


        $webqr = 'index.php/duo/' . $list['id'];
        $this->qrcode = $this->qrcode('http://' . 'www.qq6789.com' . '/' . $webqr, $list['id']);
        $this->display();
    }

    public function qrcode($text = 'http://xx.w6cc.com', $tid, $size = '4', $level = 'L', $padding = 2, $logo = true)
    {
        $path = './Public/png/';
        $QR = $path . $tid . '.png';
        vendor("Phpqrcode.phpqrcode");
        \QRcode::png($text, $QR, $level, $size, $padding);
        imagepng($QR);
        return $tid;
    }

    /**
     * 添加用户
     */
    public function add()
    {
        //默认显示添加表单
        if (!IS_POST) {
            $this->fid = session('homeId');
            $this->display();
        }
        if (IS_POST) {
            //如果用户提交数据
            $model = D("Member");
            if (!$model->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
                exit();
            } else {
                if ($model->add()) {
                    $this->success("用户添加成功", U('index/index'));
                } else {
                    $this->error("用户添加失败");
                }
            }
        }
    }

    /**
     * 更新管理员信息
     * @param  [type] $id [管理员ID]
     * @return [type]     [description]
     */
    public function update()
    {
        //默认显示添加表单
        if (!IS_POST) {
            $id = I('id');
            $uid = session('homeId');
            if ($id !== $uid) {
                $this->error('请正确提交');
            }

            $model = M('member')->find($id);
            $this->fid = $uid;
            $this->assign('model', $model);
            $this->display();
        }
        if (IS_POST) {
            $model = D("Member");
            if (!$model->create()) {
                $this->error($model->getError());
            } else {
                //验证密码是否为空
                $data = I();
                unset($data['password']);
                if (I('password') != "") {
                    $data['password'] = md5(I('password'));
                }
                //强制更改超级管理员用户类型
                if (C('SUPER_ADMIN_ID') == I('id')) {
                    $data['type'] = 2;
                }
                //更新
                if ($model->save($data)) {
                    $this->success("用户信息更新成功", U('member/index'));
                } else {
                    $this->error("未做任何修改,用户信息更新失败");
                }
            }
        }
    }


    public function checkpass()
    {

        if ($_POST) {
            if (empty($_POST['checkid'])) {
                $this->error('没有此APP信息');
            }

            $model = M('List');
            $where['id'] = trim($_POST['checkid']);
            $where['aqpassword'] = trim($_POST['aqpassword']);
            $list = $model->where($where)->find();
            if ($list) {
                //session('passid'.trim($_POST['checkid'],trim($_POST['checkid']));
                session('aqpassword' . trim($_POST['checkid']), trim($_POST['aqpassword']));
                $this->success("提交正确，跳转中...", U('Appipa/listll', array('passid' => trim($_POST['checkid']))));
            } else {
                $this->error("信息错误");
            }
        }


    }


    public function index2()
    {
        $ispayed = 0;
        //获取 路径
        $xxid = trim(I('xxid'));

        $model = M('List');
        $where = array();
        //路径赋值给shorturl 字段方便查找
        $where['shorturl'] = $xxid;
        $upid = $model->where($where)->getField('upid');
        //该字段不清楚是什么意思 应该是upid 应该是升级版本吧
        if ($upid !== '0') {
            $where = array();
            $where['id'] = $upid;
        }
        //根据网页查询
        $list = $model->where($where)->find();
        $moban = ($list['mobanid']+1);
        //没有结果跳转到错误页面
        if (!$list) {
            redirect(U('Login/nopage'));
            exit;
        }
        //实例化合并页面
        $hebing = M("Hebing");
        $where = array();
        //根据listid 查询hebing表中的appid 两个字段值是相等的
        $where['appid'] = $list['id'];
        $apparr = $hebing->where($where)->select();
        //echo "<pre>";print_r($apparr);
        //手机端判断是否有结果
        $isios = '3';
        if ($apparr) {
//            $isios = '0';//手机登录判断
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
                $isios = '1';
            } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
                $isios = '0';
            } else {
                $isios = '3';
            }
            $newid = 0;
            if ($isios != '3') {
                /**
                 * 根据页面编号进入 查询 结果看是否是 安卓还是苹果 如果是苹果进入 再次判断isios 是否等于0 安卓 0 进入 不是就跳出
                 * 否则如果是安卓 就跳入到下一个else中 看isios 是否等于1 如果是1 就是苹果 进入 如果不是就跳出
                 */
                if ($list['ext'] == 'ipa') {
                    if (!$isios) {
                        foreach ($apparr as $val) {
                            $appinfoarr = $model->where(array('id' => $val['toaddid']))->find();
                            if ($appinfoarr['ext'] != 'ipa') {
                                $newid = $appinfoarr['id'];
                                break;
                            }
                        }
                    }
                } else {
                    if ($isios) {
                        foreach ($apparr as $val) {
                            $appinfoarr = $model->where(array('id' => $val['toaddid']))->find();
                            if ($appinfoarr['ext'] == 'ipa') {
                                $newid = $appinfoarr['id'];
                                break;
                            }
                        }
                    }
                }

                if ($newid) {
                    $list = $model->where(array('id' => $newid))->find();
                    if (!$list) {
                        redirect(U('Login/nopage'));
                        exit;
                    }
                }
            }

        }
        if ($isios == '3' && $apparr) {
            $newid = 0;
            foreach ($apparr as $val) {
                $appinfoarr = $model->where(array('id' => $val['toaddid']))->find();

                $newid = $appinfoarr['id'];

            }
            if ($newid) {
                $lists = $model->where(array('id' => $newid))->find();
                if (!$list) {
                    redirect(U('Login/nopage'));
                    exit;
                }
            }


        }
        //$res = $model->where(array('id'=>$list['id']))->setInc('xznum','1');

        $downhistory = M("Downhistory");
        $nowtime = time();
        $data = array();
        $data['appid'] = $list['id'];
        $data['addtime'] = date('Y-m-d H:i:s', $nowtime);
        $data['type'] = '0';
        $downhistory->add($data);

        $uptype = M("Member")->where(array('id' => $list['fid']))->getField('uptype');

        $this->uptype = $uptype;
        $this->list = $list;
        //判断是应用是否合并
        if ($lists) {
            $this->lists = $lists;
            //调用方法 返回二维码 钱数
            $arrays = AppipaController::gopayurl($lists);

                $ispayeds = $arrays["ispayed"];
                $gopayurls  = $arrays["gopayurl"];
              //  $mobans =  $arrays["moban"];
                $this->ispayeds=$ispayeds;
                $this->gopayurls=$gopayurls;

        }
        $array = AppipaController::gopayurl($list);
            $gopayurl  = $array["gopayurl"];
            $userid =  $array["userid"];
            $ispayed = $array["ispayed"];
          //  $moban =  $array["moban"];
        $this->assign('gopayurl',$gopayurl); //如果两个需要返回两个数据

             $this->userid = $userid; //返回一个
             $this->ispayed = $ispayed;
             //模板跳转如果 lists 存在 并且 list 模板是1 或者2 跳转到3  如果lists 存在 并且 list 是4跳转到 4
            if($lists &&($moban ==1 || $moban==2)){
                $this->display('moban_3');
            }else{
                $this->display('moban_'.$moban);
            }


//             if($lists){
//                 $this->display('moban_3');
//             }else{
//              $this->display('moban_'.$moban);
//             }
    }

    /**
     * 返回数据的公共方法
     * @param $list 接收model
     * @return array 返回数组
     */
    public function gopayurl($list){
        //echo $list['upid'];exit;
        if ($list['upid'] !== '0') {
            //$web = 'a/'.$list['shorturl'];
            //$this->qrcode = $this->qrcode('http://'.$_SERVER['SERVER_NAME'].'/'.$web,$list['upid']);
            $this->qrcode = $this->qrcode('http://'.'www.qq6789.com'.$list['web'],$list['id']);
        } else {
            //echo "[".'http://'.$_SERVER['SERVER_NAME'].$list['web']."]";exit;
            $this->qrcode = $this->qrcode('http://'.'www.qq6789.com'.$list['web'],$list['id']);
        }
       // $moban = ($list['mobanid']+1);
        $ispayed = 0;
        if($list['needmoney']==0){
            $ispayed = '1';
        }

        if($list['needmoney']==1){
            $userarr = M('Member')->where(array('id'=>session('homeId')))->find();
            $fuserarr = M('Member')->where(array('id'=>$list['fid']))->find();



            $appsize = formatBytesMb($list['zsize']);
            $neednum = 1;
            $config = M("Config")->find();
            $filesizearr = explode(',',$config['filesizearr']);
            $downnumarr = explode(',',$config['downnumarr']);
            foreach($filesizearr as $k=>$val){
                if($appsize>$val){
                    $neednum = $downnumarr[$k];
                }
            }
            if($fuserarr['everydaynum']>=$neednum){
                $ispayed = '1';
            }else{
                if($fuserarr['downnum']>=$neednum){
                    $ispayed = '1';
                }else{
                    $ispayed = '0';
                }
            }



        }
        $payedcount = M("taocanorder")->where(array('userid'=>session('homeId'),'listid'=>$list['id'],'status'=>'1'))->count();
        if($payedcount){
            $ispayed = '1';
        }
        if(session('homeId')){
            $userid = session('homeId');
        }else{
            $userid = 0;
        }

        if ( is_mobile() ) {
            $gopayurl = '/alipay/wappay/payapp.php?listid='.$list['id'].'&userid='.$userid.'&buymoney='.$list['needmoney'].'';
        }else{
            $gopayurl = '/alipaypc/pagepay/payapp.php?listid='.$list['id'].'&userid='.$userid.'&buymoney='.$list['needmoney'].'';
        }
        $array = array();
        $array["gopayurl"] = $gopayurl = U("Appipa/buyapp",array('id'=>$list['id']));
        $array["userid"] = $userid;
        $array["ispayed"] = $ispayed;
     //   $array["moban"] = $moban;

        return $array;

    }

    public function downloading(){
        $id = trim(I('id'));
        $model = M('List');
        $list = $model->where("id = $id")->find();
        $this->list=$list;

        $articles = M('Articles')->limit(4)->where("startTime < now() and now() < endTime and spare1 = 1 ")->order('rand()')->select();
        $this->articles=$articles;
        $this->display();
    }
}
